// 使用 const 定义 AI 对话的异步方法
import {Message, UserType} from "./storage/ApiConversation.ts";
import {XRequest} from "@ant-design/x";
import {getServerConfig} from "./ApiConfiguration.tsx";
import {getFormattedDateWithLocale} from "./storage/ApiPredict.ts";

const KEY_REFRESH_TIME = "refreshTime"
const KEY_SERVER_CONFIG = "serverConfig"
export let serverConfig = {
    server: "",
    url: "",
    token: "",
    model: "",
    message: ""
};
const nowDate = getFormattedDateWithLocale(true)
while (serverConfig.server.length == 0 || nowDate != localStorage.getItem(KEY_REFRESH_TIME)) {
    // 使用 await 来获取结果
    const init = async () => {
        try {
            serverConfig = await getServerConfig();
            console.log(serverConfig);
            // 这里可以继续处理 serverConfig
            localStorage.setItem(KEY_REFRESH_TIME, nowDate)
            localStorage.setItem(KEY_SERVER_CONFIG, JSON.stringify(serverConfig))
        } catch (error) {
            console.error('获取服务器配置失败:', error);
        }
    };
    await init()
}
serverConfig = JSON.parse(localStorage.getItem(KEY_SERVER_CONFIG)!)


const exampleRequest = XRequest({
    baseURL: serverConfig.url,
    model: serverConfig.model,
    dangerouslyApiKey: serverConfig.token
});

const preHandleMessages = (messages: Message[]) => {
    return messages.filter(value => value.role == UserType.User || value.role == UserType.AI || value.role == UserType.System)
}
export const aiStreamConversation = async (conversationMessages: Message[],
                                           onSuccessCallback: (message: Message) => void,
                                           onError: (error: Error) => void,
                                           onUpdate: (message: string) => void) => {
    await exampleRequest.create(
        {
            messages: preHandleMessages(conversationMessages),
            stream: true,
        },
        {
            onSuccess: (json) => {
                let content = ''
                for (const i in json) {
                    const data = json[i].data
                    if (data.trim() != "[DONE]") {
                        content += JSON.parse(data).choices[0].delta.content
                    }
                }
                onSuccessCallback({role: UserType.AI, content: content})
            },
            onError: (error) => {
                onError(error);
            },
            onUpdate: (msg) => {
                if (msg.data.trim() != "[DONE]") {
                    onUpdate(JSON.parse(msg.data).choices[0].delta.content)
                }
            },
        },
    );
}